package com.zkzx.util.map;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zkzx.util.exception.UrilException;
import com.zkzx.util.http.HttpClient;
import com.zkzx.util.map.vo.AMapPoiVO;
import com.zkzx.util.map.vo.AMapRouteVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import org.springframework.stereotype.Component;

import java.util.List;

@Slf4j
@Component
public class AMapUtil {
    private static String key = "600ebaa12d82db6bc101e1c6b7da7b16";

    /**
     * 高德api 关键字模糊查询
     *
     * @param keyWord   关键字
     * @param city 可选值：城市中文、中文全拼、citycode、adcode
     * 接口文档地址   https://lbs.amap.com/api/webservice/guide/api/search
     */
    public List<AMapPoiVO> getKeywordsAddByLbs(String keyWord, String city) {

        log.error("高德api 关键字模糊查询 入参 keyWord: {}, city : {}", keyWord, city);

            StringBuilder s = new StringBuilder();
            s.append("key=").append(key).append("&keywords=");
            if (keyWord.contains(" ")) {
                String[] str = keyWord.split(" ");
                for (int i = 0; i < str.length; i++) {
                    if (i == 0) {
                        s.append(str[i]);
                    } else {
                        s.append("+").append(str[i]);
                    }
                }
            } else {
                s.append(keyWord);
            }
            //经实际验证 关键字模糊重合度过高时,city 参数不起作用;
            s.append("&city=").append(city);
            s.append("offset=20&page=1");
        String result = HttpClient.sendGet("http://restapi.amap.com/v3/place/text", s.toString());

        //因高德接口稳定性较差,数据强转后取出所需数据,如返回其余消息体,统一处理成失败;
        JSONObject jsonObject= (JSONObject) JSON.parse(result);

        //结果状态值，值为0或1, 0：请求失败；1：请求成功
        if("0".equals(jsonObject.getString("status"))){
            throw new UrilException(HttpStatus.SC_BAD_REQUEST, jsonObject.getString("info"));
        }

        JSONArray poisArray = jsonObject.getJSONArray("pois");

        //高德内容过大,数据二次拆解后返回;
        String poisArrayString = poisArray.toJSONString();
        List<AMapPoiVO> aMapPoisVOS = JSONArray.parseArray(poisArrayString, AMapPoiVO.class);

        log.error("高德api 关键字模糊查询 出参  List<AMapPoi> : {}", aMapPoisVOS.toString());

        if(aMapPoisVOS.isEmpty()){
            throw new UrilException(HttpStatus.SC_BAD_REQUEST, "高德api 关键字模糊查询 需精确地址");
        }

        return aMapPoisVOS;
    }

    /**
     * 高德地图WebAPI : 驾车路径规划 计算两地之间行驶的距离(米)
     * String origins:起始坐标
     * String destination:终点坐标
     *输入：原坐标:{116.45925,39.910031}，目标坐标:{116.587922,40.081577}
     *输出：25424
     *接口文档地址 https://lbs.amap.com/api/webservice/guide/api/direction/
     */
    public AMapRouteVO distance(String origins, String destination) {

        String s = "origin=" + origins + "&destination=" + destination +
                    "&output=json" + "&extensions=base" + "&key=" + key;

        log.error("高德api 驾车路径规划 入参 origins: {}, destination : {}", origins, destination);

        String result = HttpClient.sendGet("https://restapi.amap.com/v3/direction/driving", s);

        //因高德接口稳定性较差,数据强转后取出所需数据,如返回其余消息体,统一处理成失败;
        JSONObject jsonObject= (JSONObject) JSON.parse(result);

        //结果状态值，值为0或1, 0：请求失败；1：请求成功
        if("0".equals(jsonObject.getString("status"))){
            throw new UrilException(HttpStatus.SC_BAD_REQUEST, jsonObject.getString("info"));
        }

        //高德内容过大,数据二次拆解后返回; 此处可以使用简写 jsonObject.getObject(), 但为方便看数据, 拆分两步转换;
        JSONObject routeJSONObject = jsonObject.getJSONObject("route");
        AMapRouteVO aMapRouteVo = JSONObject.parseObject(routeJSONObject.toJSONString(), AMapRouteVO.class);

        if(aMapRouteVo.getPaths().isEmpty()){
            throw new UrilException(HttpStatus.SC_BAD_REQUEST, "高德api 驾车路径规划 需核对起止坐标");
        }
        return aMapRouteVo;
    }
}
